package histograma;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ale
 */
public class vtnPrincipal extends javax.swing.JFrame {

    
    private JFileChooser fc;
    private File imagen;
    private GestorImagen GestorImagenOriginal;
    
    /**
     * Creates new form vtnPrincipal
     */
    public vtnPrincipal() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblDIreccion = new javax.swing.JLabel();
        btnBuscar = new javax.swing.JButton();
        pnlImagenOriginal = new javax.swing.JPanel();
        lblInfoPixelOriginal = new javax.swing.JLabel();
        btnHistogramaOriginal = new javax.swing.JButton();
        pnlImagenGrises = new javax.swing.JPanel();
        Original = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        lblInfoPixelGrises = new javax.swing.JLabel();
        btnHistogramaGrises = new javax.swing.JButton();
        pnlImagenSegmentada = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        umbralSegmentacion1 = new javax.swing.JSlider();
        jLabel4 = new javax.swing.JLabel();
        lblValorUmbralSegmentacion1 = new javax.swing.JLabel();
        btnAplicarUmbralSegmentacion1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblDIreccion.setText("jLabel1");
        lblDIreccion.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        pnlImagenOriginal.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlImagenOriginal.setPreferredSize(new java.awt.Dimension(200, 200));
        pnlImagenOriginal.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                pnlImagenOriginalMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout pnlImagenOriginalLayout = new javax.swing.GroupLayout(pnlImagenOriginal);
        pnlImagenOriginal.setLayout(pnlImagenOriginalLayout);
        pnlImagenOriginalLayout.setHorizontalGroup(
            pnlImagenOriginalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 198, Short.MAX_VALUE)
        );
        pnlImagenOriginalLayout.setVerticalGroup(
            pnlImagenOriginalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 198, Short.MAX_VALUE)
        );

        lblInfoPixelOriginal.setText("jLabel1");
        lblInfoPixelOriginal.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btnHistogramaOriginal.setText("Ver Histograma");
        btnHistogramaOriginal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnHistogramaOriginalActionPerformed(evt);
            }
        });

        pnlImagenGrises.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlImagenGrises.setPreferredSize(new java.awt.Dimension(200, 200));
        pnlImagenGrises.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                pnlImagenGrisesMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout pnlImagenGrisesLayout = new javax.swing.GroupLayout(pnlImagenGrises);
        pnlImagenGrises.setLayout(pnlImagenGrisesLayout);
        pnlImagenGrisesLayout.setHorizontalGroup(
            pnlImagenGrisesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 198, Short.MAX_VALUE)
        );
        pnlImagenGrisesLayout.setVerticalGroup(
            pnlImagenGrisesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 198, Short.MAX_VALUE)
        );

        Original.setText("Original");

        jLabel1.setText("Tono de Gris");

        lblInfoPixelGrises.setText("jLabel1");
        lblInfoPixelGrises.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btnHistogramaGrises.setText("Ver Histograma");
        btnHistogramaGrises.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnHistogramaGrisesActionPerformed(evt);
            }
        });

        pnlImagenSegmentada.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlImagenSegmentada.setPreferredSize(new java.awt.Dimension(200, 200));

        javax.swing.GroupLayout pnlImagenSegmentadaLayout = new javax.swing.GroupLayout(pnlImagenSegmentada);
        pnlImagenSegmentada.setLayout(pnlImagenSegmentadaLayout);
        pnlImagenSegmentadaLayout.setHorizontalGroup(
            pnlImagenSegmentadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 198, Short.MAX_VALUE)
        );
        pnlImagenSegmentadaLayout.setVerticalGroup(
            pnlImagenSegmentadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 198, Short.MAX_VALUE)
        );

        jLabel2.setText("Umbralado Directo");

        jLabel3.setText("(preferiblemente max 200x200 px)");

        umbralSegmentacion1.setMaximum(255);
        umbralSegmentacion1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                umbralSegmentacion1StateChanged(evt);
            }
        });

        jLabel4.setText("Valor del umbral:");

        lblValorUmbralSegmentacion1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btnAplicarUmbralSegmentacion1.setText("Aplicar");
        btnAplicarUmbralSegmentacion1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAplicarUmbralSegmentacion1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addComponent(Original)
                .addGap(182, 182, 182)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(68, 68, 68))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblInfoPixelOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(pnlImagenOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnHistogramaOriginal))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(pnlImagenGrises, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblInfoPixelGrises, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(btnHistogramaGrises))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(pnlImagenSegmentada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(umbralSegmentacion1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblValorUmbralSegmentacion1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnAplicarUmbralSegmentacion1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnBuscar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblDIreccion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBuscar)
                    .addComponent(jLabel3)
                    .addComponent(lblDIreccion))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(Original)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pnlImagenGrises, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pnlImagenOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pnlImagenSegmentada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblInfoPixelOriginal)
                        .addComponent(lblInfoPixelGrises))
                    .addComponent(umbralSegmentacion1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnHistogramaOriginal)
                    .addComponent(btnHistogramaGrises)
                    .addComponent(btnAplicarUmbralSegmentacion1)
                    .addComponent(jLabel4)
                    .addComponent(lblValorUmbralSegmentacion1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // Se buscara la imagen a mostrar en la pantalla
        //Se inicializa el selector de archivos si ya no esta nicializado
        if(this.getFc()==null)
        {
            this.setFc(new javax.swing.JFileChooser());
        }
        int returnVal = this.getFc().showDialog(this.rootPane, null);
        //capturar la direccion del archivo seleccionado
        if (returnVal == this.getFc().APPROVE_OPTION)
        {
            this.setImagen(this.getFc().getSelectedFile());
            //Se mostrara en un label la direccion absoluta del archivo seleccionado
            this.lblDIreccion.setText(this.getImagen().getAbsolutePath());
            //Se pasara al Gestor de Imagen la direccion del archivo seleccionado
            //if(this.getGestorImagenOriginal()==null)
            //{
                this.setGestorImagenOriginal(new GestorImagen());
            //}
            //Se inicializa la variable de imagen
            this.getGestorImagenOriginal().cargarImagen(this.getImagen().getAbsolutePath());
            //Se muestra en el lblDireccion la direccion de la imagen seleccionada
            this.lblDIreccion.setText(this.getImagen().getAbsolutePath());
            repaint();
        }
    }//GEN-LAST:event_btnBuscarActionPerformed
/**
 * Se buscará informacion sobre el pixel seleccionado con el mouse y 
 * se mostrará en el lbl correspondiente
 * @param evt 
 */
    private void pnlImagenOriginalMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlImagenOriginalMouseClicked
        try
        {
        this.lblInfoPixelOriginal.setText(this.getGestorImagenOriginal().getInfoPixel(evt.getX(),evt.getY()));
        }
        catch(NullPointerException eNPE)
        {
            this.lblInfoPixelOriginal.setText("Debe seleccionar una imagen");
        }
        catch(ArrayIndexOutOfBoundsException eIOB)
        {
            this.lblInfoPixelOriginal.setText("Solo hacer click sobre la imagen");
        }
    }//GEN-LAST:event_pnlImagenOriginalMouseClicked

    private void pnlImagenGrisesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlImagenGrisesMouseClicked
        try
        {
        this.lblInfoPixelGrises.setText(this.getGestorImagenOriginal().getInfoPixelGris(evt.getX(),evt.getY()));
        }
        catch(NullPointerException eNPE)
        {
            this.lblInfoPixelOriginal.setText("Debe seleccionar una imagen");
        }
        catch(ArrayIndexOutOfBoundsException eIOB)
        {
            this.lblInfoPixelOriginal.setText("Solo hacer click sobre la imagen");
        }
    }//GEN-LAST:event_pnlImagenGrisesMouseClicked

    private void btnHistogramaGrisesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHistogramaGrisesActionPerformed
        try
        {
            //se calculará en vector de niveles de gris
            this.GestorImagenOriginal.setVectorHistogramaGrises();
            Histograma Panel = new Histograma(this.GestorImagenOriginal.getVectorHistogramaGrises());
        }        
        catch(NullPointerException eNPE)
        {
            this.lblInfoPixelOriginal.setText("Debe seleccionar una imagen");
        }
    }//GEN-LAST:event_btnHistogramaGrisesActionPerformed

    private void btnHistogramaOriginalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHistogramaOriginalActionPerformed
        try
        {
            //se calculará en vector de niveles de gris
            this.GestorImagenOriginal.setMatrizHistogramaColor();
            Histograma Panel = new Histograma(this.GestorImagenOriginal.getMatrizHistogramaColor());
        }        
        catch(NullPointerException eNPE)
        {
            this.lblInfoPixelOriginal.setText("Debe seleccionar una imagen");
        }
    }//GEN-LAST:event_btnHistogramaOriginalActionPerformed

    private void umbralSegmentacion1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_umbralSegmentacion1StateChanged
        //se mostrara el el valor seleccionado del umbral
        this.lblValorUmbralSegmentacion1.setText(String.valueOf(this.umbralSegmentacion1.getValue()));
    }//GEN-LAST:event_umbralSegmentacion1StateChanged

    private void btnAplicarUmbralSegmentacion1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAplicarUmbralSegmentacion1ActionPerformed
        //Se mostrara la imagen umbralizada
        int umbral = this.umbralSegmentacion1.getValue();
        this.getGestorImagenOriginal().CrearImagenUmbralizada(umbral);
        this.repaint();
    }//GEN-LAST:event_btnAplicarUmbralSegmentacion1ActionPerformed

    @Override
    public void paint(Graphics g)
    {
        //Llamada a la instruccion super.paint(g) para mantener la configuracion base
        super.paint(g);
        if(this.getGestorImagenOriginal()!=null)
        {
            //Se obtiene la instancia Graphics del panel
            Graphics gPanel = this.pnlImagenOriginal.getGraphics();
            //Se grafica la imagen en el panel
            gPanel.drawImage(   this.GestorImagenOriginal.getImgPanel(),
                                0,
                                0,
                                this
                            );
            //Se obtiene la instancia Graphics del panel de grises
            Graphics gPanelGrises = this.pnlImagenGrises.getGraphics();
            //Se grafica la imagen en el panel de grises
            gPanelGrises.drawImage  ( 
                                    this.GestorImagenOriginal.getImgPanelGrises(),
                                    0, 
                                    0, 
                                    this
                                    );
            if(this.getGestorImagenOriginal().isDibujarImagenUmbalizada())
            {
                Graphics gPanelUmbral = this.pnlImagenSegmentada.getGraphics();
                gPanelUmbral.drawImage  (
                                        this.getGestorImagenOriginal().getImgFiltrada(),
                                        0,
                                        0,
                                        this
                                        );
            }
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(vtnPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(vtnPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(vtnPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(vtnPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new vtnPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Original;
    private javax.swing.JButton btnAplicarUmbralSegmentacion1;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnHistogramaGrises;
    private javax.swing.JButton btnHistogramaOriginal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lblDIreccion;
    private javax.swing.JLabel lblInfoPixelGrises;
    private javax.swing.JLabel lblInfoPixelOriginal;
    private javax.swing.JLabel lblValorUmbralSegmentacion1;
    private javax.swing.JPanel pnlImagenGrises;
    private javax.swing.JPanel pnlImagenOriginal;
    private javax.swing.JPanel pnlImagenSegmentada;
    private javax.swing.JSlider umbralSegmentacion1;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the fc
     */
    public JFileChooser getFc() {
        return fc;
    }

    /**
     * @param fc the fc to set
     */
    public void setFc(JFileChooser fc) {
        this.fc = fc;
    }

    /**
     * @return the imagen
     */
    public File getImagen() {
        return imagen;
    }

    /**
     * @param imagen the imagen to set
     */
    public void setImagen(File imagen) {
        this.imagen = imagen;
    }

    /**
     * @return the GestorImagenOriginal
     */
    public GestorImagen getGestorImagenOriginal() {
        return GestorImagenOriginal;
    }

    /**
     * @param GestorImagenOriginal the GestorImagenOriginal to set
     */
    public void setGestorImagenOriginal(GestorImagen GestorImagenOriginal) {
        this.GestorImagenOriginal = GestorImagenOriginal;
    }
}
